Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [9]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [10]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [19]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

The face detector detects 98/100 faces in Human images and 12/100 faces in Dog Images

In [13]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
face_detector_v = np.vectorize(face_detector)
human_performance = np.sum(face_detector_v(human_files_short))
dog_performance = np.sum(face_detector_v(dog_files_short))

print("The face detector accuracy in Human files is {} % \n".format(human_performance))
print("The face detector accuracy in Dog files is {} % \n".format(dog_performance))
The face detector accuracy in Human files is 99 % 

The face detector accuracy in Dog files is 12 % 

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: As a Sofware Engineer our goal is for our product to be as simple and easy to use to our customers, I think that though reasonable to ask the customer to input a clear view of the face but the definition of clear would make it slightly inconvenient for the user. My suggestion is to try with better models and try to achieve better performance with more data and remove this restriction to a certain degree. I found many articles and research papers with Human level performance models, I think we can try using them.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [74]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
In [15]:
import mtcnn
In [20]:
detector = mtcnn.MTCNN()
In [25]:
x = detector.detect_faces(cv2.imread(human_files_short[0]))
In [27]:
x[0]['confidence']
Out[27]:
0.9997997879981995
In [60]:
def deep_face_detector(img_path):
    detector = mtcnn.MTCNN()
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    face = detector.detect_faces(img)
    result = [i for i in face if i['confidence']>0.6]
    return len(result)>0
In [64]:
h_h = [1 for i in human_files_short if deep_face_detector(i)]
In [65]:
sum(h_h)
Out[65]:
100
In [66]:
d_h = [1 for i in dog_files_short if deep_face_detector(i)]
In [67]:
sum(d_h)
Out[67]:
23
In [58]:
d = deep_face_detector_v(dog_files_short)
In [59]:
np.sum(d)
Out[59]:
23
In [61]:
d_h = [detector.detect_faces( cv2.cvtColor(cv2.imread(i), cv2.COLOR_BGR2RGB)) for i in human_files_short]
In [68]:
h_h = [detector.detect_faces( cv2.cvtColor(cv2.imread(i), cv2.COLOR_BGR2RGB)) for i in dog_files_short]
In [72]:
h_h[i]
Out[72]:
[{'box': [126, 173, 31, 36],
  'confidence': 0.8927405476570129,
  'keypoints': {'left_eye': (139, 185),
   'right_eye': (149, 186),
   'nose': (144, 195),
   'mouth_left': (137, 197),
   'mouth_right': (146, 199)}}]
In [73]:
for i in range(len(h_h)):
    if len(h_h[i])>0:
        img = cv2.cvtColor(cv2.imread(dog_files_short[i]), cv2.COLOR_BGR2RGB)
        faces = h_h[i]
        for face in faces:
            x,y,w,h=face['box']
            # add bounding box to color image
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        plt.imshow(img)
        plt.show()
        print(h_h[i])
[{'box': [615, 309, 50, 56], 'confidence': 0.8318081498146057, 'keypoints': {'left_eye': (630, 329), 'right_eye': (650, 330), 'nose': (636, 340), 'mouth_left': (627, 353), 'mouth_right': (645, 354)}}]
[{'box': [242, 66, 59, 68], 'confidence': 0.8503813147544861, 'keypoints': {'left_eye': (262, 92), 'right_eye': (276, 93), 'nose': (265, 98), 'mouth_left': (259, 108), 'mouth_right': (271, 109)}}]
[{'box': [208, 186, 31, 39], 'confidence': 0.8893977999687195, 'keypoints': {'left_eye': (222, 201), 'right_eye': (236, 200), 'nose': (231, 212), 'mouth_left': (224, 219), 'mouth_right': (237, 218)}}]
[{'box': [62, 194, 128, 154], 'confidence': 0.9066728353500366, 'keypoints': {'left_eye': (109, 245), 'right_eye': (155, 256), 'nose': (126, 259), 'mouth_left': (99, 292), 'mouth_right': (133, 301)}}]
[{'box': [238, 130, 38, 49], 'confidence': 0.9999738931655884, 'keypoints': {'left_eye': (252, 154), 'right_eye': (269, 151), 'nose': (264, 164), 'mouth_left': (254, 169), 'mouth_right': (270, 167)}}]
[{'box': [210, 592, 27, 30], 'confidence': 0.8691332340240479, 'keypoints': {'left_eye': (218, 606), 'right_eye': (227, 600), 'nose': (224, 609), 'mouth_left': (224, 617), 'mouth_right': (232, 612)}}]
[{'box': [94, 89, 49, 56], 'confidence': 0.9992958307266235, 'keypoints': {'left_eye': (106, 116), 'right_eye': (128, 108), 'nose': (122, 123), 'mouth_left': (115, 136), 'mouth_right': (134, 128)}}]
[{'box': [581, 1242, 27, 36], 'confidence': 0.7405456900596619, 'keypoints': {'left_eye': (597, 1257), 'right_eye': (608, 1256), 'nose': (608, 1265), 'mouth_left': (598, 1273), 'mouth_right': (607, 1272)}}]
[{'box': [293, 96, 21, 25], 'confidence': 0.7441531419754028, 'keypoints': {'left_eye': (301, 106), 'right_eye': (310, 106), 'nose': (306, 109), 'mouth_left': (302, 115), 'mouth_right': (309, 115)}}]
[{'box': [233, 155, 127, 191], 'confidence': 0.9019524455070496, 'keypoints': {'left_eye': (272, 229), 'right_eye': (334, 230), 'nose': (294, 279), 'mouth_left': (277, 307), 'mouth_right': (324, 307)}}]
[{'box': [582, 575, 25, 31], 'confidence': 0.7122540473937988, 'keypoints': {'left_eye': (587, 588), 'right_eye': (597, 585), 'nose': (592, 591), 'mouth_left': (591, 600), 'mouth_right': (599, 597)}}]
[{'box': [227, 23, 146, 188], 'confidence': 0.9629541039466858, 'keypoints': {'left_eye': (275, 92), 'right_eye': (339, 84), 'nose': (301, 113), 'mouth_left': (277, 167), 'mouth_right': (326, 162)}}, {'box': [39, 45, 144, 180], 'confidence': 0.7054499983787537, 'keypoints': {'left_eye': (70, 119), 'right_eye': (135, 104), 'nose': (103, 132), 'mouth_left': (88, 183), 'mouth_right': (141, 170)}}]
[{'box': [157, 170, 27, 33], 'confidence': 0.746236264705658, 'keypoints': {'left_eye': (168, 183), 'right_eye': (181, 181), 'nose': (177, 189), 'mouth_left': (170, 196), 'mouth_right': (182, 195)}}]
[{'box': [292, 118, 29, 34], 'confidence': 0.7889877557754517, 'keypoints': {'left_eye': (303, 128), 'right_eye': (313, 130), 'nose': (306, 138), 'mouth_left': (300, 142), 'mouth_right': (306, 144)}}]
[{'box': [75, 49, 175, 203], 'confidence': 0.8944777250289917, 'keypoints': {'left_eye': (133, 115), 'right_eye': (204, 122), 'nose': (160, 145), 'mouth_left': (128, 189), 'mouth_right': (187, 196)}}]
[{'box': [39, 73, 165, 221], 'confidence': 0.7400209307670593, 'keypoints': {'left_eye': (117, 162), 'right_eye': (190, 168), 'nose': (168, 212), 'mouth_left': (111, 251), 'mouth_right': (175, 258)}}]
[{'box': [335, 133, 20, 25], 'confidence': 0.8952280282974243, 'keypoints': {'left_eye': (345, 142), 'right_eye': (354, 142), 'nose': (350, 148), 'mouth_left': (345, 153), 'mouth_right': (353, 153)}}]
[{'box': [312, 237, 30, 35], 'confidence': 0.7281123995780945, 'keypoints': {'left_eye': (322, 251), 'right_eye': (333, 246), 'nose': (331, 258), 'mouth_left': (326, 265), 'mouth_right': (335, 261)}}]
[{'box': [155, 236, 38, 48], 'confidence': 0.7900809049606323, 'keypoints': {'left_eye': (161, 260), 'right_eye': (174, 253), 'nose': (166, 266), 'mouth_left': (169, 279), 'mouth_right': (180, 272)}}]
[{'box': [408, 108, 52, 67], 'confidence': 0.9109426140785217, 'keypoints': {'left_eye': (432, 140), 'right_eye': (450, 140), 'nose': (445, 154), 'mouth_left': (431, 163), 'mouth_right': (446, 163)}}]
[{'box': [132, 87, 85, 103], 'confidence': 0.8101168274879456, 'keypoints': {'left_eye': (156, 126), 'right_eye': (193, 120), 'nose': (175, 137), 'mouth_left': (163, 166), 'mouth_right': (194, 163)}}]
[{'box': [92, 107, 325, 442], 'confidence': 0.9757206439971924, 'keypoints': {'left_eye': (257, 282), 'right_eye': (387, 322), 'nose': (363, 379), 'mouth_left': (233, 441), 'mouth_right': (347, 473)}}]
[{'box': [126, 173, 31, 36], 'confidence': 0.8927405476570129, 'keypoints': {'left_eye': (139, 185), 'right_eye': (149, 186), 'nose': (144, 195), 'mouth_left': (137, 197), 'mouth_right': (146, 199)}}]

Optional

The MTCNN gets 100/100 in the human dataset and makes some miscalssifications in the dog dataset, more than the Haar cascade method. Playing around with the threshold might help solve this issue to a certain extent.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [75]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 3s 0us/step

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [76]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [77]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [78]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

The percentage of images in human_files_short detected as dog is 3 %

The percentage of images in human_files_short detected as dog is 100 %

In [79]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
h_p = sum([1 for i in human_files_short if dog_detector(i)])
d_p = sum([1 for i in dog_files_short if dog_detector(i)])
In [80]:
print("The percentage of images in human_files_short detected as dog is {} % \n".format(h_p))
print("The percentage of images in human_files_short detected as dog is {} % \n".format(d_p))
The percentage of images in human_files_short detected as dog is 3 % 

The percentage of images in human_files_short detected as dog is 100 % 


Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [81]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [00:53<00:00, 125.79it/s]
100%|██████████| 835/835 [00:06<00:00, 137.64it/s]
100%|██████████| 836/836 [00:06<00:00, 139.32it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer: Had 2 Conv layers with 32 filters of 3x3 kernels with maxpool of 2x2 and added a conv layer of 64 filters and 3x3 kernels with 2x2 maxpool then flattened to get 50176 which was passed into feedforward network of 256 nodes with relu and then to provide 133 outputs with softmax activation function. The number of params shot up when we add more dense layers so stuck with 256.

In [176]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(filters=32, kernel_size=3, padding='same', activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2,padding='same'))
model.add(Conv2D(filters=32, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2,padding='same'))
model.add(Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2,padding='same'))
model.add(Flatten())
model.add(Dense(256,activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(133,activation = 'softmax'))

model.summary()
Model: "sequential_14"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_12304 (Conv2D)        (None, 224, 224, 32)      896       
_________________________________________________________________
max_pooling2d_6131 (MaxPooli (None, 112, 112, 32)      0         
_________________________________________________________________
conv2d_12305 (Conv2D)        (None, 112, 112, 32)      9248      
_________________________________________________________________
max_pooling2d_6132 (MaxPooli (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_12306 (Conv2D)        (None, 56, 56, 64)        18496     
_________________________________________________________________
max_pooling2d_6133 (MaxPooli (None, 28, 28, 64)        0         
_________________________________________________________________
flatten_2044 (Flatten)       (None, 50176)             0         
_________________________________________________________________
dense_7154 (Dense)           (None, 256)               12845312  
_________________________________________________________________
dropout_9 (Dropout)          (None, 256)               0         
_________________________________________________________________
dense_7155 (Dense)           (None, 133)               34181     
=================================================================
Total params: 12,908,133
Trainable params: 12,908,133
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [177]:
model.compile(optimizer=optimizers.RMSprop(learning_rate=0.0001,decay=1e-6 ), loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [178]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 15

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/15
6680/6680 [==============================] - 8s 1ms/step - loss: 4.8821 - accuracy: 0.0120 - val_loss: 4.8505 - val_accuracy: 0.0263

Epoch 00001: val_loss improved from inf to 4.85052, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 2/15
6680/6680 [==============================] - 8s 1ms/step - loss: 4.7996 - accuracy: 0.0223 - val_loss: 4.7507 - val_accuracy: 0.0335

Epoch 00002: val_loss improved from 4.85052 to 4.75073, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 3/15
6680/6680 [==============================] - 8s 1ms/step - loss: 4.6542 - accuracy: 0.0401 - val_loss: 4.6132 - val_accuracy: 0.0359

Epoch 00003: val_loss improved from 4.75073 to 4.61316, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 4/15
6680/6680 [==============================] - 8s 1ms/step - loss: 4.4835 - accuracy: 0.0563 - val_loss: 4.4895 - val_accuracy: 0.0503

Epoch 00004: val_loss improved from 4.61316 to 4.48950, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 5/15
6680/6680 [==============================] - 8s 1ms/step - loss: 4.2813 - accuracy: 0.0749 - val_loss: 4.3952 - val_accuracy: 0.0683

Epoch 00005: val_loss improved from 4.48950 to 4.39525, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 6/15
6680/6680 [==============================] - 8s 1ms/step - loss: 4.0458 - accuracy: 0.1069 - val_loss: 4.3160 - val_accuracy: 0.0599

Epoch 00006: val_loss improved from 4.39525 to 4.31601, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 7/15
6680/6680 [==============================] - 8s 1ms/step - loss: 3.7743 - accuracy: 0.1499 - val_loss: 4.2922 - val_accuracy: 0.0731

Epoch 00007: val_loss improved from 4.31601 to 4.29221, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 8/15
6680/6680 [==============================] - 8s 1ms/step - loss: 3.4768 - accuracy: 0.1969 - val_loss: 4.2685 - val_accuracy: 0.0731

Epoch 00008: val_loss improved from 4.29221 to 4.26846, saving model to saved_models/weights.best.from_scratch.hdf5
Epoch 9/15
6680/6680 [==============================] - 8s 1ms/step - loss: 3.1503 - accuracy: 0.2579 - val_loss: 4.3058 - val_accuracy: 0.0826

Epoch 00009: val_loss did not improve from 4.26846
Epoch 10/15
6680/6680 [==============================] - 8s 1ms/step - loss: 2.8227 - accuracy: 0.3163 - val_loss: 4.3125 - val_accuracy: 0.0862

Epoch 00010: val_loss did not improve from 4.26846
Epoch 11/15
6680/6680 [==============================] - 8s 1ms/step - loss: 2.4974 - accuracy: 0.3763 - val_loss: 4.3691 - val_accuracy: 0.0826

Epoch 00011: val_loss did not improve from 4.26846
Epoch 12/15
6680/6680 [==============================] - 8s 1ms/step - loss: 2.1476 - accuracy: 0.4633 - val_loss: 4.4936 - val_accuracy: 0.0731

Epoch 00012: val_loss did not improve from 4.26846
Epoch 13/15
6680/6680 [==============================] - 8s 1ms/step - loss: 1.8348 - accuracy: 0.5344 - val_loss: 4.6347 - val_accuracy: 0.0898

Epoch 00013: val_loss did not improve from 4.26846
Epoch 14/15
6680/6680 [==============================] - 8s 1ms/step - loss: 1.5618 - accuracy: 0.5915 - val_loss: 4.9601 - val_accuracy: 0.0743

Epoch 00014: val_loss did not improve from 4.26846
Epoch 15/15
6680/6680 [==============================] - 8s 1ms/step - loss: 1.3310 - accuracy: 0.6534 - val_loss: 4.9013 - val_accuracy: 0.0778

Epoch 00015: val_loss did not improve from 4.26846
Out[178]:
<keras.callbacks.callbacks.History at 0x7f255e036e90>

Load the Model with the Best Validation Loss

In [179]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [180]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 7.5359%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [92]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [93]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_7082 (Dense)           (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [94]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [95]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 1s 170us/step - loss: 7.9907 - accuracy: 0.2310 - val_loss: 3.9010 - val_accuracy: 0.4467

Epoch 00001: val_loss improved from inf to 3.90103, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 2/20
6680/6680 [==============================] - 1s 160us/step - loss: 2.2322 - accuracy: 0.5885 - val_loss: 2.5498 - val_accuracy: 0.5737

Epoch 00002: val_loss improved from 3.90103 to 2.54982, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 3/20
6680/6680 [==============================] - 1s 158us/step - loss: 1.2662 - accuracy: 0.7341 - val_loss: 2.2389 - val_accuracy: 0.6323

Epoch 00003: val_loss improved from 2.54982 to 2.23886, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 4/20
6680/6680 [==============================] - 1s 158us/step - loss: 0.8018 - accuracy: 0.8126 - val_loss: 2.1151 - val_accuracy: 0.6539

Epoch 00004: val_loss improved from 2.23886 to 2.11512, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 5/20
6680/6680 [==============================] - 1s 160us/step - loss: 0.5577 - accuracy: 0.8630 - val_loss: 1.9827 - val_accuracy: 0.6838

Epoch 00005: val_loss improved from 2.11512 to 1.98268, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 6/20
6680/6680 [==============================] - 1s 158us/step - loss: 0.3971 - accuracy: 0.8957 - val_loss: 2.0146 - val_accuracy: 0.6850

Epoch 00006: val_loss did not improve from 1.98268
Epoch 7/20
6680/6680 [==============================] - 1s 159us/step - loss: 0.3004 - accuracy: 0.9192 - val_loss: 1.9130 - val_accuracy: 0.6946

Epoch 00007: val_loss improved from 1.98268 to 1.91295, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 8/20
6680/6680 [==============================] - 1s 159us/step - loss: 0.2220 - accuracy: 0.9355 - val_loss: 2.0601 - val_accuracy: 0.7078

Epoch 00008: val_loss did not improve from 1.91295
Epoch 9/20
6680/6680 [==============================] - 1s 159us/step - loss: 0.1698 - accuracy: 0.9519 - val_loss: 2.0090 - val_accuracy: 0.7281

Epoch 00009: val_loss did not improve from 1.91295
Epoch 10/20
6680/6680 [==============================] - 1s 158us/step - loss: 0.1301 - accuracy: 0.9621 - val_loss: 1.9527 - val_accuracy: 0.7246

Epoch 00010: val_loss did not improve from 1.91295
Epoch 11/20
6680/6680 [==============================] - 1s 160us/step - loss: 0.1000 - accuracy: 0.9689 - val_loss: 1.9690 - val_accuracy: 0.7150

Epoch 00011: val_loss did not improve from 1.91295
Epoch 12/20
6680/6680 [==============================] - 1s 160us/step - loss: 0.0789 - accuracy: 0.9753 - val_loss: 2.0198 - val_accuracy: 0.7210

Epoch 00012: val_loss did not improve from 1.91295
Epoch 13/20
6680/6680 [==============================] - 1s 159us/step - loss: 0.0599 - accuracy: 0.9799 - val_loss: 2.0653 - val_accuracy: 0.7305

Epoch 00013: val_loss did not improve from 1.91295
Epoch 14/20
6680/6680 [==============================] - 1s 159us/step - loss: 0.0480 - accuracy: 0.9846 - val_loss: 1.9989 - val_accuracy: 0.7353

Epoch 00014: val_loss did not improve from 1.91295
Epoch 15/20
6680/6680 [==============================] - 1s 160us/step - loss: 0.0408 - accuracy: 0.9865 - val_loss: 2.0519 - val_accuracy: 0.7425

Epoch 00015: val_loss did not improve from 1.91295
Epoch 16/20
6680/6680 [==============================] - 1s 159us/step - loss: 0.0359 - accuracy: 0.9897 - val_loss: 2.1384 - val_accuracy: 0.7329

Epoch 00016: val_loss did not improve from 1.91295
Epoch 17/20
6680/6680 [==============================] - 1s 160us/step - loss: 0.0303 - accuracy: 0.9903 - val_loss: 2.0839 - val_accuracy: 0.7437

Epoch 00017: val_loss did not improve from 1.91295
Epoch 18/20
6680/6680 [==============================] - 1s 158us/step - loss: 0.0272 - accuracy: 0.9928 - val_loss: 2.1402 - val_accuracy: 0.7365

Epoch 00018: val_loss did not improve from 1.91295
Epoch 19/20
6680/6680 [==============================] - 1s 172us/step - loss: 0.0249 - accuracy: 0.9943 - val_loss: 2.1295 - val_accuracy: 0.7425

Epoch 00019: val_loss did not improve from 1.91295
Epoch 20/20
6680/6680 [==============================] - 1s 176us/step - loss: 0.0198 - accuracy: 0.9943 - val_loss: 2.2192 - val_accuracy: 0.7425

Epoch 00020: val_loss did not improve from 1.91295
Out[95]:
<keras.callbacks.callbacks.History at 0x7f2570c00ed0>

Load the Model with the Best Validation Loss

In [96]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [97]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 69.0191%

Predict Dog Breed with the Model

In [145]:
from extract_bottleneck_features import *

def Xception_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [ ]:
 
In [146]:
print(Xception_predict_breed('images/American_water_spaniel_00648.jpg'))
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.4/xception_weights_tf_dim_ordering_tf_kernels_notop.h5
83689472/83683744 [==============================] - 2s 0us/step
Curly-coated_retriever
In [ ]:
 

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [107]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
networks = ['VGG19','Resnet50','InceptionV3','Xception']
for network in networks:
    exec(f"bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')")
    exec(f"train_{network} = bottleneck_features['train']")
    exec(f"valid_{network} = bottleneck_features['valid']")
    exec(f"test_{network} = bottleneck_features['test']")
In [110]:
train_InceptionV3.shape,train_VGG19.shape,train_Xception.shape,train_Resnet50.shape
Out[110]:
((6680, 5, 5, 2048), (6680, 7, 7, 512), (6680, 7, 7, 2048), (6680, 1, 1, 2048))

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Tried adding a Dense hidden layer with 512 nodes and dropout to prevent overfitting and then to 133 outputs of activation for each of the pre-trained mdoels - VGG19,Resnet50,InceptionV3 and Xception... Overall found Resnet50,InceptionV3 and Xception having similar performance(~2-3% difference) and Xception model performing best overall in test so chose to go with Xception model. Also GPU run times for all the models - Resnet50,InceptionV3 and Xception were comparable so went with the best.

In [112]:
### TODO: Define your architecture.
InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalAveragePooling2D(input_shape=train_InceptionV3.shape[1:]))
InceptionV3_model.add(Dense(512,activation ='relu'))
InceptionV3_model.add(Dropout(0.5))
InceptionV3_model.add(Dense(133, activation='softmax'))
print("\n InceptionV3 Model Summary: \n")
InceptionV3_model.summary()

VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(512,activation ='relu'))
VGG19_model.add(Dropout(0.5))
VGG19_model.add(Dense(133, activation='softmax'))
print("\n VGG19 Model Summary: \n")
VGG19_model.summary()


Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(512,activation ='relu'))
Resnet50_model.add(Dropout(0.5))
Resnet50_model.add(Dense(133, activation='softmax'))
print("\n Resnet50 Model Summary: \n")
Resnet50_model.summary()

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(512,activation ='relu'))
Xception_model.add(Dropout(0.5))
Xception_model.add(Dense(133, activation='softmax'))
print("\n Xception Model Summary: \n")
Xception_model.summary()
 InceptionV3 Model Summary: 

Model: "sequential_8"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 2048)              0         
_________________________________________________________________
dense_7087 (Dense)           (None, 512)               1049088   
_________________________________________________________________
dropout_4 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_7088 (Dense)           (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________

 VGG19 Model Summary: 

Model: "sequential_9"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_5 ( (None, 512)               0         
_________________________________________________________________
dense_7089 (Dense)           (None, 512)               262656    
_________________________________________________________________
dropout_5 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_7090 (Dense)           (None, 133)               68229     
=================================================================
Total params: 330,885
Trainable params: 330,885
Non-trainable params: 0
_________________________________________________________________

 Resnet50 Model Summary: 

Model: "sequential_10"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_6 ( (None, 2048)              0         
_________________________________________________________________
dense_7091 (Dense)           (None, 512)               1049088   
_________________________________________________________________
dropout_6 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_7092 (Dense)           (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________

 Xception Model Summary: 

Model: "sequential_11"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_7 ( (None, 2048)              0         
_________________________________________________________________
dense_7093 (Dense)           (None, 512)               1049088   
_________________________________________________________________
dropout_7 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_7094 (Dense)           (None, 133)               68229     
=================================================================
Total params: 1,117,317
Trainable params: 1,117,317
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [114]:
### TODO: Compile the model.
from keras import optimizers

InceptionV3_model.compile(loss='categorical_crossentropy', 
                        optimizer=optimizers.RMSprop(0.0001, decay=1e-6), 
                        metrics=['accuracy'])

Resnet50_model.compile(loss='categorical_crossentropy', 
                        optimizer=optimizers.RMSprop(0.0001, decay=1e-6), 
                        metrics=['accuracy'])
VGG19_model.compile(loss='categorical_crossentropy', 
                        optimizer=optimizers.RMSprop(0.0001, decay=1e-6), 
                        metrics=['accuracy'])
Xception_model.compile(loss='categorical_crossentropy', 
                        optimizer=optimizers.RMSprop(0.0001, decay=1e-6), 
                        metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [138]:
### TODO: Train the model.

checkpointer_VGG19 = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_acc = VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=40, batch_size=20, callbacks=[checkpointer_VGG19], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6680/6680 [==============================] - 1s 182us/step - loss: 0.0706 - accuracy: 0.9754 - val_loss: 1.0425 - val_accuracy: 0.7868

Epoch 00001: val_loss improved from inf to 1.04253, saving model to saved_models/weights.best.VGG19.hdf5
Epoch 2/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0736 - accuracy: 0.9763 - val_loss: 1.0756 - val_accuracy: 0.7760

Epoch 00002: val_loss did not improve from 1.04253
Epoch 3/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0731 - accuracy: 0.9759 - val_loss: 1.0587 - val_accuracy: 0.7868

Epoch 00003: val_loss did not improve from 1.04253
Epoch 4/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0684 - accuracy: 0.9780 - val_loss: 1.0586 - val_accuracy: 0.7856

Epoch 00004: val_loss did not improve from 1.04253
Epoch 5/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0778 - accuracy: 0.9751 - val_loss: 1.0518 - val_accuracy: 0.7880

Epoch 00005: val_loss did not improve from 1.04253
Epoch 6/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0702 - accuracy: 0.9780 - val_loss: 1.0617 - val_accuracy: 0.7796

Epoch 00006: val_loss did not improve from 1.04253
Epoch 7/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0646 - accuracy: 0.9783 - val_loss: 1.0981 - val_accuracy: 0.7844

Epoch 00007: val_loss did not improve from 1.04253
Epoch 8/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0744 - accuracy: 0.9766 - val_loss: 1.0605 - val_accuracy: 0.7844

Epoch 00008: val_loss did not improve from 1.04253
Epoch 9/40
6680/6680 [==============================] - 1s 182us/step - loss: 0.0709 - accuracy: 0.9777 - val_loss: 1.0748 - val_accuracy: 0.7868

Epoch 00009: val_loss did not improve from 1.04253
Epoch 10/40
6680/6680 [==============================] - 1s 184us/step - loss: 0.0707 - accuracy: 0.9798 - val_loss: 1.0858 - val_accuracy: 0.7868

Epoch 00010: val_loss did not improve from 1.04253
Epoch 11/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0645 - accuracy: 0.9790 - val_loss: 1.0662 - val_accuracy: 0.7880

Epoch 00011: val_loss did not improve from 1.04253
Epoch 12/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0651 - accuracy: 0.9780 - val_loss: 1.0758 - val_accuracy: 0.7784

Epoch 00012: val_loss did not improve from 1.04253
Epoch 13/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0648 - accuracy: 0.9790 - val_loss: 1.0714 - val_accuracy: 0.7808

Epoch 00013: val_loss did not improve from 1.04253
Epoch 14/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0691 - accuracy: 0.9780 - val_loss: 1.0749 - val_accuracy: 0.7796

Epoch 00014: val_loss did not improve from 1.04253
Epoch 15/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0517 - accuracy: 0.9826 - val_loss: 1.0681 - val_accuracy: 0.7904

Epoch 00015: val_loss did not improve from 1.04253
Epoch 16/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0568 - accuracy: 0.9820 - val_loss: 1.1056 - val_accuracy: 0.7832

Epoch 00016: val_loss did not improve from 1.04253
Epoch 17/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0599 - accuracy: 0.9787 - val_loss: 1.1250 - val_accuracy: 0.7832

Epoch 00017: val_loss did not improve from 1.04253
Epoch 18/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0627 - accuracy: 0.9804 - val_loss: 1.1091 - val_accuracy: 0.7808

Epoch 00018: val_loss did not improve from 1.04253
Epoch 19/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0601 - accuracy: 0.9819 - val_loss: 1.1035 - val_accuracy: 0.7916

Epoch 00019: val_loss did not improve from 1.04253
Epoch 20/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0558 - accuracy: 0.9810 - val_loss: 1.1239 - val_accuracy: 0.7916

Epoch 00020: val_loss did not improve from 1.04253
Epoch 21/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0634 - accuracy: 0.9781 - val_loss: 1.1412 - val_accuracy: 0.7808

Epoch 00021: val_loss did not improve from 1.04253
Epoch 22/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0578 - accuracy: 0.9822 - val_loss: 1.1338 - val_accuracy: 0.7916

Epoch 00022: val_loss did not improve from 1.04253
Epoch 23/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0541 - accuracy: 0.9834 - val_loss: 1.1528 - val_accuracy: 0.7868

Epoch 00023: val_loss did not improve from 1.04253
Epoch 24/40
6680/6680 [==============================] - 1s 181us/step - loss: 0.0494 - accuracy: 0.9853 - val_loss: 1.1303 - val_accuracy: 0.7820

Epoch 00024: val_loss did not improve from 1.04253
Epoch 25/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0544 - accuracy: 0.9829 - val_loss: 1.0771 - val_accuracy: 0.7892

Epoch 00025: val_loss did not improve from 1.04253
Epoch 26/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0496 - accuracy: 0.9826 - val_loss: 1.1350 - val_accuracy: 0.7820

Epoch 00026: val_loss did not improve from 1.04253
Epoch 27/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0608 - accuracy: 0.9810 - val_loss: 1.1234 - val_accuracy: 0.7796

Epoch 00027: val_loss did not improve from 1.04253
Epoch 28/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0491 - accuracy: 0.9838 - val_loss: 1.0920 - val_accuracy: 0.7976

Epoch 00028: val_loss did not improve from 1.04253
Epoch 29/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0479 - accuracy: 0.9843 - val_loss: 1.1339 - val_accuracy: 0.7832

Epoch 00029: val_loss did not improve from 1.04253
Epoch 30/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0471 - accuracy: 0.9846 - val_loss: 1.1632 - val_accuracy: 0.7880

Epoch 00030: val_loss did not improve from 1.04253
Epoch 31/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0441 - accuracy: 0.9855 - val_loss: 1.1599 - val_accuracy: 0.7880

Epoch 00031: val_loss did not improve from 1.04253
Epoch 32/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0567 - accuracy: 0.9829 - val_loss: 1.1785 - val_accuracy: 0.7856

Epoch 00032: val_loss did not improve from 1.04253
Epoch 33/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0412 - accuracy: 0.9853 - val_loss: 1.1857 - val_accuracy: 0.7904

Epoch 00033: val_loss did not improve from 1.04253
Epoch 34/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0548 - accuracy: 0.9831 - val_loss: 1.1918 - val_accuracy: 0.7904

Epoch 00034: val_loss did not improve from 1.04253
Epoch 35/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0498 - accuracy: 0.9847 - val_loss: 1.2113 - val_accuracy: 0.7904

Epoch 00035: val_loss did not improve from 1.04253
Epoch 36/40
6680/6680 [==============================] - 1s 180us/step - loss: 0.0573 - accuracy: 0.9822 - val_loss: 1.1826 - val_accuracy: 0.7904

Epoch 00036: val_loss did not improve from 1.04253
Epoch 37/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0513 - accuracy: 0.9835 - val_loss: 1.1434 - val_accuracy: 0.7868

Epoch 00037: val_loss did not improve from 1.04253
Epoch 38/40
6680/6680 [==============================] - 1s 178us/step - loss: 0.0405 - accuracy: 0.9864 - val_loss: 1.1986 - val_accuracy: 0.7880

Epoch 00038: val_loss did not improve from 1.04253
Epoch 39/40
6680/6680 [==============================] - 1s 179us/step - loss: 0.0423 - accuracy: 0.9855 - val_loss: 1.2090 - val_accuracy: 0.7844

Epoch 00039: val_loss did not improve from 1.04253
Epoch 40/40
6680/6680 [==============================] - 1s 178us/step - loss: 0.0438 - accuracy: 0.9858 - val_loss: 1.1870 - val_accuracy: 0.7988

Epoch 00040: val_loss did not improve from 1.04253
In [139]:
checkpointer_Resnet50 = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)

Resnet50_acc = Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=40, batch_size=20, callbacks=[checkpointer_Resnet50], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0123 - accuracy: 0.9964 - val_loss: 0.6547 - val_accuracy: 0.8551

Epoch 00001: val_loss improved from inf to 0.65467, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 2/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0124 - accuracy: 0.9964 - val_loss: 0.6289 - val_accuracy: 0.8563

Epoch 00002: val_loss improved from 0.65467 to 0.62888, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 3/40
6680/6680 [==============================] - 1s 140us/step - loss: 0.0138 - accuracy: 0.9969 - val_loss: 0.6469 - val_accuracy: 0.8527

Epoch 00003: val_loss did not improve from 0.62888
Epoch 4/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0144 - accuracy: 0.9958 - val_loss: 0.6278 - val_accuracy: 0.8599

Epoch 00004: val_loss improved from 0.62888 to 0.62784, saving model to saved_models/weights.best.Resnet50.hdf5
Epoch 5/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0118 - accuracy: 0.9966 - val_loss: 0.6317 - val_accuracy: 0.8587

Epoch 00005: val_loss did not improve from 0.62784
Epoch 6/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0099 - accuracy: 0.9973 - val_loss: 0.6432 - val_accuracy: 0.8563

Epoch 00006: val_loss did not improve from 0.62784
Epoch 7/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0103 - accuracy: 0.9969 - val_loss: 0.6527 - val_accuracy: 0.8575

Epoch 00007: val_loss did not improve from 0.62784
Epoch 8/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0114 - accuracy: 0.9967 - val_loss: 0.6534 - val_accuracy: 0.8575

Epoch 00008: val_loss did not improve from 0.62784
Epoch 9/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0114 - accuracy: 0.9964 - val_loss: 0.6655 - val_accuracy: 0.8563

Epoch 00009: val_loss did not improve from 0.62784
Epoch 10/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0121 - accuracy: 0.9964 - val_loss: 0.6539 - val_accuracy: 0.8623

Epoch 00010: val_loss did not improve from 0.62784
Epoch 11/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0099 - accuracy: 0.9970 - val_loss: 0.6636 - val_accuracy: 0.8623

Epoch 00011: val_loss did not improve from 0.62784
Epoch 12/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0103 - accuracy: 0.9969 - val_loss: 0.6750 - val_accuracy: 0.8611

Epoch 00012: val_loss did not improve from 0.62784
Epoch 13/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0115 - accuracy: 0.9979 - val_loss: 0.6756 - val_accuracy: 0.8563

Epoch 00013: val_loss did not improve from 0.62784
Epoch 14/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0086 - accuracy: 0.9976 - val_loss: 0.6531 - val_accuracy: 0.8551

Epoch 00014: val_loss did not improve from 0.62784
Epoch 15/40
6680/6680 [==============================] - 1s 141us/step - loss: 0.0086 - accuracy: 0.9975 - val_loss: 0.6696 - val_accuracy: 0.8599

Epoch 00015: val_loss did not improve from 0.62784
Epoch 16/40
6680/6680 [==============================] - 1s 140us/step - loss: 0.0113 - accuracy: 0.9972 - val_loss: 0.6662 - val_accuracy: 0.8575

Epoch 00016: val_loss did not improve from 0.62784
Epoch 17/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0087 - accuracy: 0.9981 - val_loss: 0.6770 - val_accuracy: 0.8635

Epoch 00017: val_loss did not improve from 0.62784
Epoch 18/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0082 - accuracy: 0.9979 - val_loss: 0.6799 - val_accuracy: 0.8563

Epoch 00018: val_loss did not improve from 0.62784
Epoch 19/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0079 - accuracy: 0.9978 - val_loss: 0.6815 - val_accuracy: 0.8683

Epoch 00019: val_loss did not improve from 0.62784
Epoch 20/40
6680/6680 [==============================] - 1s 140us/step - loss: 0.0082 - accuracy: 0.9981 - val_loss: 0.7120 - val_accuracy: 0.8611

Epoch 00020: val_loss did not improve from 0.62784
Epoch 21/40
6680/6680 [==============================] - 1s 141us/step - loss: 0.0084 - accuracy: 0.9976 - val_loss: 0.6955 - val_accuracy: 0.8563

Epoch 00021: val_loss did not improve from 0.62784
Epoch 22/40
6680/6680 [==============================] - 1s 141us/step - loss: 0.0075 - accuracy: 0.9979 - val_loss: 0.6966 - val_accuracy: 0.8587

Epoch 00022: val_loss did not improve from 0.62784
Epoch 23/40
6680/6680 [==============================] - 1s 141us/step - loss: 0.0074 - accuracy: 0.9975 - val_loss: 0.6737 - val_accuracy: 0.8587

Epoch 00023: val_loss did not improve from 0.62784
Epoch 24/40
6680/6680 [==============================] - 1s 141us/step - loss: 0.0081 - accuracy: 0.9972 - val_loss: 0.6782 - val_accuracy: 0.8599

Epoch 00024: val_loss did not improve from 0.62784
Epoch 25/40
6680/6680 [==============================] - 1s 139us/step - loss: 0.0099 - accuracy: 0.9975 - val_loss: 0.6712 - val_accuracy: 0.8611

Epoch 00025: val_loss did not improve from 0.62784
Epoch 26/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0097 - accuracy: 0.9964 - val_loss: 0.7254 - val_accuracy: 0.8479

Epoch 00026: val_loss did not improve from 0.62784
Epoch 27/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0074 - accuracy: 0.9979 - val_loss: 0.6945 - val_accuracy: 0.8491

Epoch 00027: val_loss did not improve from 0.62784
Epoch 28/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0079 - accuracy: 0.9975 - val_loss: 0.6957 - val_accuracy: 0.8563

Epoch 00028: val_loss did not improve from 0.62784
Epoch 29/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0107 - accuracy: 0.9973 - val_loss: 0.7081 - val_accuracy: 0.8611

Epoch 00029: val_loss did not improve from 0.62784
Epoch 30/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0092 - accuracy: 0.9978 - val_loss: 0.7181 - val_accuracy: 0.8575

Epoch 00030: val_loss did not improve from 0.62784
Epoch 31/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0100 - accuracy: 0.9976 - val_loss: 0.7091 - val_accuracy: 0.8443

Epoch 00031: val_loss did not improve from 0.62784
Epoch 32/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0081 - accuracy: 0.9987 - val_loss: 0.7157 - val_accuracy: 0.8527

Epoch 00032: val_loss did not improve from 0.62784
Epoch 33/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0077 - accuracy: 0.9976 - val_loss: 0.7155 - val_accuracy: 0.8515

Epoch 00033: val_loss did not improve from 0.62784
Epoch 34/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0078 - accuracy: 0.9978 - val_loss: 0.6965 - val_accuracy: 0.8527

Epoch 00034: val_loss did not improve from 0.62784
Epoch 35/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0066 - accuracy: 0.9984 - val_loss: 0.7183 - val_accuracy: 0.8515

Epoch 00035: val_loss did not improve from 0.62784
Epoch 36/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0073 - accuracy: 0.9984 - val_loss: 0.6970 - val_accuracy: 0.8647

Epoch 00036: val_loss did not improve from 0.62784
Epoch 37/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0099 - accuracy: 0.9973 - val_loss: 0.7159 - val_accuracy: 0.8587

Epoch 00037: val_loss did not improve from 0.62784
Epoch 38/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0104 - accuracy: 0.9975 - val_loss: 0.7074 - val_accuracy: 0.8623

Epoch 00038: val_loss did not improve from 0.62784
Epoch 39/40
6680/6680 [==============================] - 1s 138us/step - loss: 0.0064 - accuracy: 0.9984 - val_loss: 0.7327 - val_accuracy: 0.8515

Epoch 00039: val_loss did not improve from 0.62784
Epoch 40/40
6680/6680 [==============================] - 1s 137us/step - loss: 0.0106 - accuracy: 0.9976 - val_loss: 0.7295 - val_accuracy: 0.8467

Epoch 00040: val_loss did not improve from 0.62784
In [140]:
checkpointer_Xception = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_acc = Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=40, batch_size=20, callbacks=[checkpointer_Xception], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0113 - accuracy: 0.9975 - val_loss: 0.7194 - val_accuracy: 0.8419

Epoch 00001: val_loss improved from inf to 0.71937, saving model to saved_models/weights.best.Xception.hdf5
Epoch 2/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0094 - accuracy: 0.9982 - val_loss: 0.7125 - val_accuracy: 0.8467

Epoch 00002: val_loss improved from 0.71937 to 0.71246, saving model to saved_models/weights.best.Xception.hdf5
Epoch 3/40
6680/6680 [==============================] - 2s 333us/step - loss: 0.0094 - accuracy: 0.9979 - val_loss: 0.7004 - val_accuracy: 0.8503

Epoch 00003: val_loss improved from 0.71246 to 0.70039, saving model to saved_models/weights.best.Xception.hdf5
Epoch 4/40
6680/6680 [==============================] - 2s 334us/step - loss: 0.0091 - accuracy: 0.9979 - val_loss: 0.7124 - val_accuracy: 0.8479

Epoch 00004: val_loss did not improve from 0.70039
Epoch 5/40
6680/6680 [==============================] - 2s 334us/step - loss: 0.0109 - accuracy: 0.9970 - val_loss: 0.6903 - val_accuracy: 0.8515

Epoch 00005: val_loss improved from 0.70039 to 0.69030, saving model to saved_models/weights.best.Xception.hdf5
Epoch 6/40
6680/6680 [==============================] - 2s 335us/step - loss: 0.0103 - accuracy: 0.9967 - val_loss: 0.6980 - val_accuracy: 0.8491

Epoch 00006: val_loss did not improve from 0.69030
Epoch 7/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0085 - accuracy: 0.9979 - val_loss: 0.7299 - val_accuracy: 0.8491

Epoch 00007: val_loss did not improve from 0.69030
Epoch 8/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0093 - accuracy: 0.9978 - val_loss: 0.7066 - val_accuracy: 0.8563

Epoch 00008: val_loss did not improve from 0.69030
Epoch 9/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0124 - accuracy: 0.9963 - val_loss: 0.6918 - val_accuracy: 0.8527

Epoch 00009: val_loss did not improve from 0.69030
Epoch 10/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0086 - accuracy: 0.9981 - val_loss: 0.7325 - val_accuracy: 0.8503

Epoch 00010: val_loss did not improve from 0.69030
Epoch 11/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0093 - accuracy: 0.9981 - val_loss: 0.7267 - val_accuracy: 0.8515

Epoch 00011: val_loss did not improve from 0.69030
Epoch 12/40
6680/6680 [==============================] - 2s 335us/step - loss: 0.0094 - accuracy: 0.9978 - val_loss: 0.7027 - val_accuracy: 0.8539

Epoch 00012: val_loss did not improve from 0.69030
Epoch 13/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0106 - accuracy: 0.9976 - val_loss: 0.7087 - val_accuracy: 0.8539

Epoch 00013: val_loss did not improve from 0.69030
Epoch 14/40
6680/6680 [==============================] - 2s 329us/step - loss: 0.0099 - accuracy: 0.9978 - val_loss: 0.7242 - val_accuracy: 0.8539

Epoch 00014: val_loss did not improve from 0.69030
Epoch 15/40
6680/6680 [==============================] - 2s 330us/step - loss: 0.0093 - accuracy: 0.9978 - val_loss: 0.7473 - val_accuracy: 0.8551

Epoch 00015: val_loss did not improve from 0.69030
Epoch 16/40
6680/6680 [==============================] - 2s 330us/step - loss: 0.0086 - accuracy: 0.9979 - val_loss: 0.7350 - val_accuracy: 0.8491

Epoch 00016: val_loss did not improve from 0.69030
Epoch 17/40
6680/6680 [==============================] - 2s 329us/step - loss: 0.0071 - accuracy: 0.9982 - val_loss: 0.7338 - val_accuracy: 0.8539

Epoch 00017: val_loss did not improve from 0.69030
Epoch 18/40
6680/6680 [==============================] - 2s 328us/step - loss: 0.0084 - accuracy: 0.9975 - val_loss: 0.7490 - val_accuracy: 0.8503

Epoch 00018: val_loss did not improve from 0.69030
Epoch 19/40
6680/6680 [==============================] - 2s 328us/step - loss: 0.0074 - accuracy: 0.9978 - val_loss: 0.7525 - val_accuracy: 0.8491

Epoch 00019: val_loss did not improve from 0.69030
Epoch 20/40
6680/6680 [==============================] - 2s 329us/step - loss: 0.0084 - accuracy: 0.9981 - val_loss: 0.7639 - val_accuracy: 0.8479

Epoch 00020: val_loss did not improve from 0.69030
Epoch 21/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0098 - accuracy: 0.9976 - val_loss: 0.7211 - val_accuracy: 0.8515

Epoch 00021: val_loss did not improve from 0.69030
Epoch 22/40
6680/6680 [==============================] - 2s 328us/step - loss: 0.0085 - accuracy: 0.9972 - val_loss: 0.7317 - val_accuracy: 0.8563

Epoch 00022: val_loss did not improve from 0.69030
Epoch 23/40
6680/6680 [==============================] - 2s 327us/step - loss: 0.0078 - accuracy: 0.9982 - val_loss: 0.7479 - val_accuracy: 0.8515

Epoch 00023: val_loss did not improve from 0.69030
Epoch 24/40
6680/6680 [==============================] - 2s 327us/step - loss: 0.0081 - accuracy: 0.9979 - val_loss: 0.7572 - val_accuracy: 0.8527

Epoch 00024: val_loss did not improve from 0.69030
Epoch 25/40
6680/6680 [==============================] - 2s 327us/step - loss: 0.0096 - accuracy: 0.9973 - val_loss: 0.7625 - val_accuracy: 0.8551

Epoch 00025: val_loss did not improve from 0.69030
Epoch 26/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0087 - accuracy: 0.9981 - val_loss: 0.7547 - val_accuracy: 0.8527

Epoch 00026: val_loss did not improve from 0.69030
Epoch 27/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0115 - accuracy: 0.9973 - val_loss: 0.7773 - val_accuracy: 0.8503

Epoch 00027: val_loss did not improve from 0.69030
Epoch 28/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0080 - accuracy: 0.9976 - val_loss: 0.7871 - val_accuracy: 0.8455

Epoch 00028: val_loss did not improve from 0.69030
Epoch 29/40
6680/6680 [==============================] - 2s 332us/step - loss: 0.0071 - accuracy: 0.9978 - val_loss: 0.7526 - val_accuracy: 0.8515

Epoch 00029: val_loss did not improve from 0.69030
Epoch 30/40
6680/6680 [==============================] - 2s 334us/step - loss: 0.0102 - accuracy: 0.9979 - val_loss: 0.7432 - val_accuracy: 0.8515

Epoch 00030: val_loss did not improve from 0.69030
Epoch 31/40
6680/6680 [==============================] - 2s 328us/step - loss: 0.0077 - accuracy: 0.9976 - val_loss: 0.7617 - val_accuracy: 0.8539

Epoch 00031: val_loss did not improve from 0.69030
Epoch 32/40
6680/6680 [==============================] - 2s 329us/step - loss: 0.0084 - accuracy: 0.9978 - val_loss: 0.7588 - val_accuracy: 0.8515

Epoch 00032: val_loss did not improve from 0.69030
Epoch 33/40
6680/6680 [==============================] - 2s 331us/step - loss: 0.0067 - accuracy: 0.9979 - val_loss: 0.7735 - val_accuracy: 0.8455

Epoch 00033: val_loss did not improve from 0.69030
Epoch 34/40
6680/6680 [==============================] - 2s 329us/step - loss: 0.0080 - accuracy: 0.9976 - val_loss: 0.7797 - val_accuracy: 0.8479

Epoch 00034: val_loss did not improve from 0.69030
Epoch 35/40
6680/6680 [==============================] - 2s 342us/step - loss: 0.0070 - accuracy: 0.9982 - val_loss: 0.7791 - val_accuracy: 0.8455

Epoch 00035: val_loss did not improve from 0.69030
Epoch 36/40
6680/6680 [==============================] - 2s 343us/step - loss: 0.0080 - accuracy: 0.9978 - val_loss: 0.7733 - val_accuracy: 0.8503

Epoch 00036: val_loss did not improve from 0.69030
Epoch 37/40
6680/6680 [==============================] - 2s 335us/step - loss: 0.0064 - accuracy: 0.9982 - val_loss: 0.7901 - val_accuracy: 0.8503

Epoch 00037: val_loss did not improve from 0.69030
Epoch 38/40
6680/6680 [==============================] - 2s 330us/step - loss: 0.0061 - accuracy: 0.9982 - val_loss: 0.7771 - val_accuracy: 0.8491

Epoch 00038: val_loss did not improve from 0.69030
Epoch 39/40
6680/6680 [==============================] - 2s 328us/step - loss: 0.0078 - accuracy: 0.9978 - val_loss: 0.8117 - val_accuracy: 0.8503

Epoch 00039: val_loss did not improve from 0.69030
Epoch 40/40
6680/6680 [==============================] - 2s 327us/step - loss: 0.0072 - accuracy: 0.9978 - val_loss: 0.7787 - val_accuracy: 0.8455

Epoch 00040: val_loss did not improve from 0.69030
In [141]:
checkpointer_InceptionV3 = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', 
                               verbose=1, save_best_only=True)

InceptionV3_acc = InceptionV3_model.fit(train_InceptionV3, train_targets, 
          validation_data=(valid_InceptionV3, valid_targets),
          epochs=40, batch_size=20, callbacks=[checkpointer_InceptionV3], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6680/6680 [==============================] - 1s 223us/step - loss: 0.0146 - accuracy: 0.9964 - val_loss: 0.7910 - val_accuracy: 0.8623

Epoch 00001: val_loss improved from inf to 0.79096, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 2/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0172 - accuracy: 0.9952 - val_loss: 0.7441 - val_accuracy: 0.8551

Epoch 00002: val_loss improved from 0.79096 to 0.74408, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 3/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0158 - accuracy: 0.9957 - val_loss: 0.7675 - val_accuracy: 0.8623

Epoch 00003: val_loss did not improve from 0.74408
Epoch 4/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0158 - accuracy: 0.9951 - val_loss: 0.7922 - val_accuracy: 0.8683

Epoch 00004: val_loss did not improve from 0.74408
Epoch 5/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0153 - accuracy: 0.9955 - val_loss: 0.7431 - val_accuracy: 0.8599

Epoch 00005: val_loss improved from 0.74408 to 0.74307, saving model to saved_models/weights.best.InceptionV3.hdf5
Epoch 6/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0140 - accuracy: 0.9955 - val_loss: 0.7680 - val_accuracy: 0.8683

Epoch 00006: val_loss did not improve from 0.74307
Epoch 7/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0158 - accuracy: 0.9958 - val_loss: 0.7764 - val_accuracy: 0.8659

Epoch 00007: val_loss did not improve from 0.74307
Epoch 8/40
6680/6680 [==============================] - 1s 223us/step - loss: 0.0136 - accuracy: 0.9958 - val_loss: 0.7629 - val_accuracy: 0.8623

Epoch 00008: val_loss did not improve from 0.74307
Epoch 9/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0118 - accuracy: 0.9960 - val_loss: 0.7452 - val_accuracy: 0.8671

Epoch 00009: val_loss did not improve from 0.74307
Epoch 10/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0123 - accuracy: 0.9957 - val_loss: 0.7797 - val_accuracy: 0.8671

Epoch 00010: val_loss did not improve from 0.74307
Epoch 11/40
6680/6680 [==============================] - 1s 219us/step - loss: 0.0152 - accuracy: 0.9957 - val_loss: 0.7883 - val_accuracy: 0.8671

Epoch 00011: val_loss did not improve from 0.74307
Epoch 12/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0110 - accuracy: 0.9978 - val_loss: 0.7907 - val_accuracy: 0.8671

Epoch 00012: val_loss did not improve from 0.74307
Epoch 13/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0147 - accuracy: 0.9969 - val_loss: 0.8121 - val_accuracy: 0.8587

Epoch 00013: val_loss did not improve from 0.74307
Epoch 14/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0117 - accuracy: 0.9963 - val_loss: 0.7895 - val_accuracy: 0.8683

Epoch 00014: val_loss did not improve from 0.74307
Epoch 15/40
6680/6680 [==============================] - 1s 220us/step - loss: 0.0115 - accuracy: 0.9960 - val_loss: 0.8127 - val_accuracy: 0.8599

Epoch 00015: val_loss did not improve from 0.74307
Epoch 16/40
6680/6680 [==============================] - 1s 220us/step - loss: 0.0101 - accuracy: 0.9967 - val_loss: 0.8324 - val_accuracy: 0.8587

Epoch 00016: val_loss did not improve from 0.74307
Epoch 17/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0150 - accuracy: 0.9952 - val_loss: 0.8138 - val_accuracy: 0.8575

Epoch 00017: val_loss did not improve from 0.74307
Epoch 18/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0108 - accuracy: 0.9963 - val_loss: 0.8028 - val_accuracy: 0.8599

Epoch 00018: val_loss did not improve from 0.74307
Epoch 19/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0127 - accuracy: 0.9966 - val_loss: 0.8331 - val_accuracy: 0.8635

Epoch 00019: val_loss did not improve from 0.74307
Epoch 20/40
6680/6680 [==============================] - 1s 220us/step - loss: 0.0127 - accuracy: 0.9963 - val_loss: 0.8067 - val_accuracy: 0.8659

Epoch 00020: val_loss did not improve from 0.74307
Epoch 21/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0112 - accuracy: 0.9970 - val_loss: 0.8112 - val_accuracy: 0.8731

Epoch 00021: val_loss did not improve from 0.74307
Epoch 22/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0118 - accuracy: 0.9963 - val_loss: 0.8469 - val_accuracy: 0.8671

Epoch 00022: val_loss did not improve from 0.74307
Epoch 23/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0090 - accuracy: 0.9973 - val_loss: 0.8516 - val_accuracy: 0.8683

Epoch 00023: val_loss did not improve from 0.74307
Epoch 24/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0090 - accuracy: 0.9975 - val_loss: 0.8512 - val_accuracy: 0.8659

Epoch 00024: val_loss did not improve from 0.74307
Epoch 25/40
6680/6680 [==============================] - 1s 223us/step - loss: 0.0106 - accuracy: 0.9970 - val_loss: 0.8394 - val_accuracy: 0.8551

Epoch 00025: val_loss did not improve from 0.74307
Epoch 26/40
6680/6680 [==============================] - 1s 225us/step - loss: 0.0111 - accuracy: 0.9972 - val_loss: 0.8468 - val_accuracy: 0.8659

Epoch 00026: val_loss did not improve from 0.74307
Epoch 27/40
6680/6680 [==============================] - 1s 220us/step - loss: 0.0095 - accuracy: 0.9975 - val_loss: 0.8666 - val_accuracy: 0.8599

Epoch 00027: val_loss did not improve from 0.74307
Epoch 28/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0099 - accuracy: 0.9973 - val_loss: 0.8311 - val_accuracy: 0.8671

Epoch 00028: val_loss did not improve from 0.74307
Epoch 29/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0101 - accuracy: 0.9967 - val_loss: 0.8394 - val_accuracy: 0.8635

Epoch 00029: val_loss did not improve from 0.74307
Epoch 30/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0096 - accuracy: 0.9973 - val_loss: 0.8803 - val_accuracy: 0.8587

Epoch 00030: val_loss did not improve from 0.74307
Epoch 31/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0111 - accuracy: 0.9969 - val_loss: 0.8565 - val_accuracy: 0.8635

Epoch 00031: val_loss did not improve from 0.74307
Epoch 32/40
6680/6680 [==============================] - 1s 222us/step - loss: 0.0105 - accuracy: 0.9973 - val_loss: 0.8758 - val_accuracy: 0.8659

Epoch 00032: val_loss did not improve from 0.74307
Epoch 33/40
6680/6680 [==============================] - 1s 224us/step - loss: 0.0089 - accuracy: 0.9978 - val_loss: 0.8789 - val_accuracy: 0.8623

Epoch 00033: val_loss did not improve from 0.74307
Epoch 34/40
6680/6680 [==============================] - 1s 224us/step - loss: 0.0116 - accuracy: 0.9970 - val_loss: 0.8661 - val_accuracy: 0.8611

Epoch 00034: val_loss did not improve from 0.74307
Epoch 35/40
6680/6680 [==============================] - 2s 225us/step - loss: 0.0116 - accuracy: 0.9967 - val_loss: 0.9028 - val_accuracy: 0.8647

Epoch 00035: val_loss did not improve from 0.74307
Epoch 36/40
6680/6680 [==============================] - 1s 224us/step - loss: 0.0087 - accuracy: 0.9964 - val_loss: 0.8875 - val_accuracy: 0.8659

Epoch 00036: val_loss did not improve from 0.74307
Epoch 37/40
6680/6680 [==============================] - 1s 224us/step - loss: 0.0107 - accuracy: 0.9972 - val_loss: 0.8754 - val_accuracy: 0.8599

Epoch 00037: val_loss did not improve from 0.74307
Epoch 38/40
6680/6680 [==============================] - 1s 223us/step - loss: 0.0104 - accuracy: 0.9967 - val_loss: 0.9111 - val_accuracy: 0.8647

Epoch 00038: val_loss did not improve from 0.74307
Epoch 39/40
6680/6680 [==============================] - 2s 225us/step - loss: 0.0077 - accuracy: 0.9978 - val_loss: 0.9161 - val_accuracy: 0.8647

Epoch 00039: val_loss did not improve from 0.74307
Epoch 40/40
6680/6680 [==============================] - 1s 221us/step - loss: 0.0093 - accuracy: 0.9970 - val_loss: 0.8947 - val_accuracy: 0.8635

Epoch 00040: val_loss did not improve from 0.74307
In [125]:
VGG19_acc.history.keys()
Out[125]:
dict_keys(['val_loss', 'val_accuracy', 'loss', 'accuracy'])
In [127]:
type(VGG19_acc.history['accuracy']),len(VGG19_acc.history['accuracy'])
Out[127]:
(list, 40)

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [142]:
### TODO: Load the model weights with the best validation loss.

print("VGG19 transfer learning model: The Best Train Accuracy is : {0:.2f} % and Best Validation Accuracy is : {1:.2f} % \n ".format(100* max(VGG19_acc.history['accuracy']),100* max(VGG19_acc.history['val_accuracy'])))
print("InceptionV3 transfer learning model: The Best Train Accuracy is : {0:.2f} % and Best Validation Accuracy is : {1:.2f} % \n ".format(100* max(InceptionV3_acc.history['accuracy']),100* max(InceptionV3_acc.history['val_accuracy'])))
print("Xception transfer learning model: The Best Train Accuracy is : {0:.2f} % and Best Validation Accuracy is : {1:.2f} % \n ".format(100* max(Xception_acc.history['accuracy']),100* max(Xception_acc.history['val_accuracy'])))
print("Resnet50 transfer learning model: The Best Train Accuracy is : {0:.2f} % and Best Validation Accuracy is : {1:.2f} % \n ".format(100* max(Resnet50_acc.history['accuracy']),100* max(Resnet50_acc.history['val_accuracy'])))
VGG19 transfer learning model: The Best Train Accuracy is : 98.64 % and Best Validation Accuracy is : 79.88 % 
 
InceptionV3 transfer learning model: The Best Train Accuracy is : 99.78 % and Best Validation Accuracy is : 87.31 % 
 
Xception transfer learning model: The Best Train Accuracy is : 99.82 % and Best Validation Accuracy is : 85.63 % 
 
Resnet50 transfer learning model: The Best Train Accuracy is : 99.87 % and Best Validation Accuracy is : 86.83 % 
 

The model with best Validation loss is InceptionV3

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [143]:
### TODO: Calculate classification accuracy on the test dataset.

VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('VGG19 model : Test accuracy : %.4f%% \n' % test_accuracy) 

Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Resnet50 model : Test accuracy : %.4f%% \n' % test_accuracy) 

InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')
InceptionV3_predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_InceptionV3]
test_accuracy = 100*np.sum(np.array(InceptionV3_predictions)==np.argmax(test_targets, axis=1))/len(InceptionV3_predictions)
print('InceptionV3 model : Test accuracy : %.4f%% \n' % test_accuracy) 

Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Xception model : Test accuracy : %.4f%% \n' % test_accuracy) 
VGG19 model : Test accuracy : 80.6220% 

Resnet50 model : Test accuracy : 83.9713% 

InceptionV3 model : Test accuracy : 83.0144% 

Xception model : Test accuracy : 86.6029% 

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [147]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

def Xception_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)[0]
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
In [151]:
print(Xception_predict_breed('images/Welsh_springer_spaniel_08203.jpg'))
Welsh_springer_spaniel
In [153]:
img = cv2.cvtColor(cv2.imread('images/Welsh_springer_spaniel_08203.jpg'), cv2.COLOR_BGR2RGB)
plt.imshow(img)
Out[153]:
<matplotlib.image.AxesImage at 0x7f256b760b10>
In [154]:
def display_img(img_path):
    img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
    plt.imshow(img)
In [ ]:
 

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [155]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def predict_human_dog(img_path):
    human = deep_face_detector(img_path)
    dog = Xception_predict_breed(img_path)
    if dog_detector(img_path):
        if not human:
            display_img(img_path)
            print("Its a dog of breed : {} \n ".format(dog))
        else:
            print("There seems to be a dog person similar to {} \n".format(dog))
    elif human:
        display_img(img_path)
        print("You sure are a dog person and sure look like a {} \n".format(dog))
        
    else:
        display_img(img_path)
        print("There is no human or dog in this image")

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: The output is fairly good, though there is huge scope for improvement.

Points of improvement:

  1. As we might have different classes in the image, it will be better to train the model with more images with multiple objects of same,different classes and also training with more negative examples will be required.
  2. Better hyper parameter tuning to improve performance along with more data.
  3. Different models can be tested a bit more deeper model perhaps.
  4. Data Augmentation should be tried to improve performance.
In [156]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
predict_human_dog('test_images/testing_image.jpg')
You sure are a dog person and sure look like a Golden_retriever 

In [157]:
predict_human_dog('test_images/test2.jpg')
You sure are a dog person and sure look like a Labrador_retriever 

In [158]:
predict_human_dog('test_images/test3.jpg')
You sure are a dog person and sure look like a Kuvasz 

In [160]:
predict_human_dog('test_images/test4.jpg')
There is no human or dog in this image
In [162]:
predict_human_dog('test_images/test5.jpg')
There is no human or dog in this image
In [163]:
Xception_predict_breed('test_images/test5.jpg')
Out[163]:
'Anatolian_shepherd_dog'
In [164]:
dog_detector('test_images/test5.jpg')
Out[164]:
False
In [165]:
predict_human_dog('test_images/test5.jpeg')
There is no human or dog in this image
In [166]:
Xception_predict_breed('test_images/test5.jpeg')
Out[166]:
'Chinese_crested'
In [167]:
dog_detector('test_images/test5.jpeg')
Out[167]:
False
In [ ]: